package com.googlecode.tracey.ui.config;

import com.googlecode.totallylazy.Bytes;
import com.googlecode.totallylazy.Callable1;
import com.googlecode.totallylazy.Sequence;
import com.googlecode.tracey.ui.core.*;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.Map;

import static com.googlecode.totallylazy.Closeables.using;
import static com.googlecode.totallylazy.Maps.get;
import static com.googlecode.totallylazy.Sequences.sequence;
import static java.util.Collections.EMPTY_LIST;

public class JsonConfigModule implements MessageServerModule, ExtensionsModule {
    private final Map<String, Object> json;

    public JsonConfigModule(final Map<String, Object> json) throws IOException {
        this.json = json;
    }

    @Override
    public Extensions addExtension(Extensions extensions) throws Exception {
        final Sequence<Extension> map = sequence(extensions()).map(Extension.fromMap());
        map.forEach(Extensions.addTo(extensions));
        return extensions;
    }

    @Override
    public MessageServers addMessageServers(MessageServers messageServers) throws Exception {
        final Sequence<MessageServer> map = sequence(messageServers()).map(MessageServer.fromMap());
        map.forEach(MessageServers.addTo(messageServers));
        return messageServers;
    }

    private List<Map<String, Object>> extensions() {
        return (List<Map<String, Object>>) get(json, "extensions").getOrElse(EMPTY_LIST);
    }

    private List<Map<String, Object>> messageServers() {
        return (List<Map<String, Object>>) get(json, "message-servers").getOrElse(EMPTY_LIST);
    }

    public static String getJson(URL configFile) throws IOException {
        return using(configFile.openStream(), new Callable1<InputStream, String>() {
                @Override
                public String call(InputStream in) throws Exception {
                    return new String(Bytes.bytes(in));
                }
            });
    }
}
